package com.liuhengjia.exception;

import com.liuhengjia.pojo.Result;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Set;

@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理 JSR-380 校验异常（ConstraintViolationException）
     *
     * @param ex jakarta.validation.ConstraintViolationException
     * @return com.liuhengjia.pojo.Result
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<String> handleConstraintViolationException(ConstraintViolationException ex) {
        Set<ConstraintViolation<?>> violations = ex.getConstraintViolations();
        if (!violations.isEmpty()) {
            // 取第一个错误作为提示
            String message = violations.iterator().next().getMessage();
            return Result.error(message);
        }
        return Result.error("参数校验失败，请检查输入");
    }

    /**
     * 处理参数校验异常（@Valid 校验失败）
     *
     * @param ex org.springframework.web.bind.MethodArgumentNotValidException
     * @return com.liuhengjia.pojo.Result
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Object> handleValidationExceptions(MethodArgumentNotValidException ex) {
        BindingResult result = ex.getBindingResult();
        String errorMessage = result.getAllErrors().get(0).getDefaultMessage();
        return Result.error(errorMessage);
    }

    /**
     * 处理其它异常
     *
     * @param e Exception
     * @return com.liuhengjia.pojo.Result
     */
    @ExceptionHandler(Exception.class)
    public Result<Object> handleOtherExceptions(Exception e) {
        e.printStackTrace();
        return Result.error("服务器开小差了，请稍后再试~~~");
    }

}
